package com.wideplay.warp.clustering.swarmcache;

import net.sf.swarmcache.ObjectCache;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.google.inject.Provider;
import com.google.inject.Key;
import com.wideplay.warp.clustering.DataGrid;

/**
 * Created with IntelliJ IDEA.
 * On: 23/06/2007
 *
 * @author Dhanji R. Prasanna
 * @since 1.0
 */
class SwarmDataGridImpl implements DataGrid {
    private ObjectCache cache;
    private final Lock lock = new ReentrantLock();


    void setCache(ObjectCache cache) {
        this.cache = cache;
    }

    public <T> void descope(Key<T> key) {
        lock.lock();
        try {
            cache.clear(key.toString());
        } finally {
            lock.unlock();
        }
    }


    public void flush() {
        
    }


    public <T> void flush(Key<T> key) {
        
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key, Provider<T> creator) {
        T object;
        lock.lock();
        try {
            object = (T) cache.get(key);

            if (null == object) {
                object = creator.get();
                cache.put(key, object);
            }

        } finally {
            lock.unlock();
        }

        return object;
    }
}
